package com.github.lh.service.impl;

import com.github.lh.common.ReturnCode;
import com.github.lh.dao.BaseRepo;
import com.github.lh.service.BaseService;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Predicate;
import groovy.util.logging.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

import static com.github.lh.common.AssertUtils.assertNotNull;


/**
 * @author <a href="mailto: 393803588@qq.com">刘涵(Hanl)</a>
 * By 2017/12/1
 */
@Slf4j
public abstract class BaseServiceImpl<T, ID extends Serializable> implements BaseService<T, ID> {

    /**
     * gen code
     *
     * @param entity
     * @param <S>
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public <S extends T> S save(S entity) {
        return getDao().save(entity);
    }

    /**
     * gen code
     *
     * @param entities
     * @param <S>
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public <S extends T> List<S> save(Iterable<S> entities) {
        return getDao().save(entities);
    }

    /**
     * gen code
     *
     * @param id
     * @return
     */
    @Override
    public T getOne(ID id) {
        assertNotNull(id, ReturnCode.BAD_REQUEST, "param.required", "id");
        return getDao().getOne(id);
    }

    /**
     * gen code
     *
     * @param predicate
     * @return
     */
    @Override
    public T findOne(Predicate predicate) {
        return getDao().findOne(predicate);
    }

    /**
     * gen code
     *
     * @param id
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void delete(ID id) {
        assertNotNull(id, ReturnCode.BAD_REQUEST, "param.required", "id");
        getDao().delete(id);
    }

    /**
     * gen code
     *
     * @param entity
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void delete(T entity) {
        getDao().delete(entity);
    }

    /**
     * gen code
     *
     * @param predicate
     * @param orders
     * @return
     */
    @Override
    public Iterable<T> findAll(Predicate predicate, OrderSpecifier<?>... orders) {
        return getDao().findAll(predicate, orders);
    }

    /**
     * gen code
     *
     * @param predicate
     * @param pageable
     * @return
     */
    @Override
    public Page<T> findAll(Predicate predicate, Pageable pageable) {
        return getDao().findAll(predicate, pageable);
    }

    abstract BaseRepo<T, ID> getDao();
}
